package practise.案例七_文件上传;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class 服务端 {
    public static void main(String[] args) throws Exception{
        ServerSocket serverSocket = new ServerSocket(55555);

        while (true) {
            Socket socket = serverSocket.accept();
            new Thread(new MyThread(socket)).start();
        }
    }
}

class MyThread implements Runnable {
    private Socket socket ;

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public MyThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //        传输文件->不能用字符流，封装成高级的字节缓冲流
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream =
                    new FileOutputStream("day11/src/practise/案例七_文件上传/file/"+ UUID.randomUUID()+".jpg");
            byte[] bytes = new byte[1024*64];
            int len ;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();

            socket.getOutputStream().write("文件上传完成".getBytes());
            System.out.println("文件上传完成");

//            关闭资源
            inputStream.close();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}